<?php

namespace addons\mplogin\library;

use app\admin\model\Admin;
use fast\Random;
use think\Config;
use think\Cookie;
use think\Session;

class Auth extends \fast\Auth
{
    protected $_error = '';
    protected $breadcrumb = [];

    public function __construct()
    {
        parent::__construct();
    }

    public function __get($name)
    {
        return  Session::get('admin.' . $name);
    }

    /**
     * 管理员登录
     *
     * @param   string $username 用户名
     * @param   string $password 密码
     * @param   int    $keeptime 有效时长
     * @return  boolean
     */
    public function login($username, $password, $keeptime = 0, $token = false)
    {
        $admin = Admin::get(['username' => $username]);
        if (!$admin) {
            $this->setError('Username is incorrect');
            return false;
        }
        if ($admin['status'] == 'hidden') {
            $this->setError('Admin is forbidden');
            return false;
        }
        $login_failure_retry = Config::get('fastadmin.login_failure_retry');
        if ($login_failure_retry && $admin->loginfailure >= 10 && time() - $admin->updatetime < 86400) {
            $this->setError('Please try again after 1 day');
            return false;
        }
        if ($token) {
            if ($admin->password != md5(md5($password) . $admin->salt)) {
                $admin->loginfailure++;
                $admin->save();
                $this->setError('Password is incorrect');
                return false;
            }
        } else {
            if ($admin->password != $password) {
                $admin->loginfailure++;
                $admin->save();
                $this->setError('Password is incorrect');
                return false;
            }
        }
        $admin->loginfailure = 0;
        $admin->logintime = time();
        $admin->loginip = request()->ip();
        $admin->token = Random::uuid();
        $admin->allowField(true)->save();
        Session::set("admin", $admin->toArray());
        return true;
    }

    public function uid2login($admin_id, $keeptime = 0)
    {
        $admin = Admin::get(['id' => $admin_id]);
        if (!$admin) {
            $this->setError('Username is incorrect');
            return false;
        }
        if ($admin['status'] == 'hidden') {
            $this->setError('Admin is forbidden');
            return false;
        }
        $login_failure_retry = Config::get('fastadmin.login_failure_retry');
        if ($login_failure_retry && $admin->loginfailure >= 10 && time() - $admin->updatetime < 86400) {
            $this->setError('Please try again after 1 day');
            return false;
        }
        $admin->loginfailure = 0;
        $admin->logintime = time();
        $admin->loginip = request()->ip();
        $admin->token = Random::uuid();
        $admin->allowField(true)->save();
        Session::set("admin", $admin->toArray());
        Session::set("admin.safecode", $this->getEncryptSafecode($admin));


        $this->keeplogin($admin, $keeptime);
        return true;
    }

    /**
     * 刷新保持登录的Cookie
     *
     * @param   int $keeptime
     * @return  boolean
     */
    protected function keeplogin($admin, $keeptime = 0)
    {

        if ($keeptime) {
            $expiretime = time() + $keeptime;
            $key = $this->getKeeploginKey($admin, $keeptime, $expiretime);
            Cookie::set('keeplogin', implode('|', [$admin['id'], $keeptime, $expiretime, $key]), $keeptime);
            return true;
        }
        return false;
    }
    /**
     * 获取自动登录Key
     * @param $params
     * @param $keeptime
     * @param $expiretime
     * @return string
     */
    public function getKeeploginKey($params, $keeptime, $expiretime)
    {
        $key = md5(md5($params['id']) . md5($keeptime) . md5($expiretime) . $params['token'] . config('token.key'));
        return $key;
    }

    /**
     * 获取加密后的安全码
     * @param $params
     * @return string
     */
    public function getEncryptSafecode($params)
    {
        return md5(md5($params['username']) . md5(substr($params['password'], 0, 6)) . config('token.key'));
    }
    /**
     * 设置错误信息
     *
     * @param string $error 错误信息
     * @return Auth
     */
    public function setError($error)
    {
        $this->_error = $error;
        return $this;
    }

    /**
     * 获取错误信息
     * @return string
     */
    public function getError()
    {
        return $this->_error ? __($this->_error) : '';
    }
}
